#按部门获取回复率
import requests
import time
import pymysql

ID = "ww7b4086d88a144eec"
SECRET = "Yy-hdts7KZHFDO8tzwWTNUfPiGyssUOo8XAPz2IOnbA"
url_get_access_token = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret=" + SECRET

#获取access_token#
def get_access_token(ID,SECRET):
    access_token_json = requests.get(url_get_access_token).json()
    while access_token_json['errcode'] != 0:
        get_access_token(ID, SECRET)
        time.sleep(2)
    access_token = access_token_json['access_token']
    return access_token

url_get_user_behavior = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_user_behavior_data?access_token=" + get_access_token(ID,SECRET)
db = pymysql.connect(host="localhost", user="root", password="zcxvbmn", database="weixindb")
cursor = db.cursor()

def get_reply_percentage(start_time, end_time):
    branch_select_sql = "SELECT id,name FROM department_list WHERE (RIGHT(`name`,2)='分部') AND LENGTH(`name`)=12"
    store_select_sql = "SELECT id,name FROM department_list WHERE (RIGHT(`name`,2)='卖场') OR `name`='合肥超级体验店'"
    cursor.execute(branch_select_sql)
    branch_list = cursor.fetchall()
    db.commit()
    cursor.execute(store_select_sql)
    store_list = cursor.fetchall()
    db.commit()
    branch_list_only_id = []
    for branch in branch_list:
        branch_list_only_id.append(branch[0])
    #将分部id列表分割为小列表组成的列表
    for branch_id in branch_list_only_id:
        branch_json = {
            "userid": [],
            "partyid": branch_id,
            "start_time": start_time,
            "end_time": end_time,
        }
        behavior_data = requests.post(url_get_user_behavior, json=branch_json).json()['behavior_data']
        print(behavior_data)
    return
get_reply_percentage(1626624000, 1627142400)